package Concurrency3_Art.chapter01;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能说明：并行的程序一定快吗?
 * 测试并行与串行程序的性能对比
 * 开发人员：@author MaLi
 */
public class T01_CheckContextSwitch_Art {
    private static int[] times = {10, 100, 1000, 10000, 100000, 1000000, 10000000};

    //并发程序
    public static void main(String[] args) {
        //并行程序执行效率
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < times.length; i++) {
            int finalI = i;

            threads.add(new Thread(() -> {
                long start = System.currentTimeMillis();
                int result = 0;
                for (int j = 0; j < times[finalI]; j++) {
                    result++;
                }
                long end = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " 次数" + times[finalI] + " 次, RunningTime:" + (end - start));
            }, "Thread" + i));
        }

        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //串行程序执行效率
        for (int i = 0; i < times.length; i++) {
            long start = System.currentTimeMillis();
            int result = 0;
            for (int j = 0; j < times[i]; j++) {
                result++;
            }
            long end = System.currentTimeMillis();
            System.err.println(Thread.currentThread().getName() + " 次数" + times[i] + " 次,  RunningTime:" + (end - start));
        }
    }
}
